<?php

namespace backend\controllers;

use Yii;
use backend\models\Commodity;
use backend\models\CommoditySearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;
use yii\data\Pagination;

/**
 * CommodityController implements the CRUD actions for Commodity model.
 */
class CommodityController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Commodity models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new CommoditySearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        // $pages = new Pagination(['totalCount' => $dataProvider->count(), 'pageSize' => 2]);
        // $model = $dataProvider->offset($pages->offset)->limit($pages->limit)->all();
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            // 'pages' => $pages,
        ]);
    }

    /**
     * Displays a single Commodity model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Commodity model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Commodity();
        $post = Yii::$app->request->post();
        $rootPath = "uploads/";
        $imgRootPath = "uploads/";
        $imgUrls = array();

        if (isset($_POST['Commodity'])) {
            $model->attributes = $_POST['Commodity'];
            // 获取细节图集
            $model->details = UploadedFile::getInstances($model, 'details'); // 获取图集资源
            $imgExt = $model->details[0]->getExtension();
            $imgRandName = time() . rand(1000, 9999) . "." . $imgExt;
            $imgPath = abs(crc32($imgRandName) % 500);
            $imgRootPath = $imgRootPath . $imgPath . "/";
            if (!file_exists($imgRootPath)) {
                mkdir($imgRootPath, true);
            };
            foreach ($model->details as $value) {
                $imgExt = $value->getExtension();
                $imgRandName = time() . rand(1000, 9999) . "." . $imgExt;
                $value->size = $imgRootPath.$imgRandName;
                $value->saveAs($imgRootPath . $imgRandName);
                $imgUrls[] = $imgRootPath.$imgRandName;
                // array_push($imgUrls, $imgRootPath.$imgRandName);
            };

            // icon 图片资源获取
            $iconUrl = UploadedFile::getInstance($model, 'icon_url'); // 获取图片资源
            $ext = $iconUrl->getExtension(); // 获取文件的扩展名
            $randName = time() . rand(1000, 9999) . "." . $ext;
            $path = abs(crc32($randName) % 500);
            $rootPath = $rootPath . $path . "/";
            if (!file_exists($path)) {
                mkdir($rootPath, true);
            };
            $iconUrl->saveAs($rootPath . $randName);

            // 存储到数据库中
            $model->details = serialize($imgUrls);
            $model->icon_url = $rootPath.$randName;

            if ($model->save()) {
                // echo $model->icon_url;
                return $this->redirect(['view', 'id' => $model->id]);
            } else {
                // echo "AAA";
            }
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Commodity model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Commodity model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Commodity model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Commodity the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Commodity::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
